import { onBeforeMount, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCountAPI, getEssayAPI } from '@/apis/essay'

const cache = {}

export default function useEssayInfo() {

  const route = useRoute()
  const router = useRouter()
  const cur = ref(0)
  const total = ref(0)
  const essay = ref(null)

  onBeforeMount(async () => {
    total.value = (await getCountAPI()).data

    cur.value = route.params.id == 'newest' ? total.value : +route.params.id
    if (cur.value > total.value) {
      router.push('/404')
      return
    }
    _getEssay(cur.value)
  })

  watch(() => route.params.id, nw => {
    cur.value = nw == 'newest' ? total.value : +nw
    _getEssay(cur.value)
  })

  async function _getEssay(id) {
    if (cache[id]) {
      essay.value = cache[id]
      return
    }

    // const info = await import(`../../../_data~/essays/${id}.json`)
    // essay.value = info.default
    getEssayAPI(id - 1).then(res => {
      essay.value = res.data
      cache[id] = res.data
    }).catch(err => {
      router.push('/404')
    })
  }

  return {
    cur,
    total,
    essay
  }

}